#coding:utf-8

import requests
import time
import json
from mysql import sqlExecute

"""
中国各省疫情情况
"""

def get_url():
    # 抓取数据
    ## 先把数据都爬下来，查看数据结构，明确要整理保存的数据
    list = []
    # url_1包含中国各省市当日实时数据
    url_1 = 'https://view.inews.qq.com/g2/getOnsInfo?name=disease_h5'
    list.append(url_1)
    # url_2包含中国历史数据及每日新增数据
    url_2 = 'https://view.inews.qq.com/g2/getOnsInfo?name=disease_other'
    list.append(url_2)
    # url_3包含全球实时数据及历史数据、中国输入病例
    url_3 = 'https://view.inews.qq.com/g2/getOnsInfo?name=disease_foreign'
    list.append(url_3)
    return list


def main():
    datalist = getData()
    result = saveData(datalist)
    if result is None:
        print("数据存储失败")
    else:
        print("数据存储成功")


#第一步：爬取网页数据
def getData():
    datalists = []
    #国内各省市当日实时数据
    time1 = int(time.time()*1000)
    url1 = get_url()[0]+f"&callback=&_=%d"%time1
    # url_2包含中国历史数据及每日新增数据
    url2 = get_url()[1]
    # url_3包含全球实时数据及历史数据、中国输入病例
    url3 = get_url()[2]
    header = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.61 Safari/537.36"}
    result = requests.get(url=url1,headers = header)
    if result.status_code == 200:
        data = json.loads(result.json()['data'])
        covid_area = data['areaTree'][0]['children']
        for i in range(0,len(covid_area)):
            datalist = ()
            area = covid_area[i]
            datalist = datalist + (data['lastUpdateTime'],)
            datalist = datalist + (str(area['name']),)
            # 当天数据
            datalist = datalist + (area['today']['confirm'],) #当天确诊
            datalist = datalist + (area['today']['confirmCuts'],)  #确诊新增
            datalist = datalist + (area['total']['nowConfirm'],) # 现存确诊
            datalist = datalist + (area['total']['confirm'],) #总确诊病例
            datalist = datalist + (area['total']['suspect'],)  #总疑似病例
            datalist = datalist + (area['total']['dead'],)  # 总死亡病例
            datalist = datalist + (area['total']['deadRate'],) #死亡率
            # total_showRate = covid_area['total']['showRate']
            datalist = datalist + (area['total']['heal'],)    #治愈人数
            datalist = datalist + (area['total']['healRate'],)  #治愈率
            # total_showHeal = covid_area['total']['showHeal']  #
            datalists.append(datalist)
        return datalists
# 第二步： 将数据保存到数据库中
def saveData(datalist):
    sqlDb = sqlExecute.MysqlDb()
    sql = "insert into covid_province(province_name,today_confirm,today_confirmCuts,total_nowConfirm,total_confirm,total_suspect,total_dead,total_deadRate,total_heal,total_healRate) " \
          "values(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)"
    result = sqlDb.execute_sql(sql,datalist)
    return result


if __name__ == "__main__":
    main()